package com.ibiaoke.common.base;

import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.exception.ValidateException;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.AssertUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * controller基础类
 * Created by huhaichao on 2017/6/20.
 */
public class BaseController {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * 处理hibernate validate验证结果
     *
     * @param result
     */
    public void handleValidate(BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            throw new ValidateException(fieldError.getDefaultMessage());
        }
    }

    /**
     * 返回错误信息给页面
     *
     * @param error
     * @return
     */
    public Res error(String error) {
        return Res.createErrorRes(error);
    }


    public <T> T getLoginUser(){
        Object loginUser = getSession().getAttribute(CommonConsts.LOGIN_SESSION_NAME);
        AssertUtils.notNull(loginUser,"not_login");
        return (T) loginUser;
    }
    public <T> T getLoginUserSafely(){
        return (T) getSession().getAttribute(CommonConsts.LOGIN_SESSION_NAME);
    }
    /**
     * 成功返回结果
     *
     * @param key
     * @param value
     * @return
     */
    public Res success(String key, Object value) {
        return Res.create().addResponse(key, value);
    }

    public void render(String msg) {
        try {
            PrintWriter writer = getResponse().getWriter();
            writer.print(msg);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Res success() {
        return Res.create();
    }

    private ServletRequestAttributes servletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    private void render(Res res) {
        try {
            getResponse().getWriter().write(res.toJson());
        } catch (IOException e) {
            throw new ServiceException("返回json给前台出错", e);
        }
    }

    /**
     * 获取request
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        return servletRequestAttributes().getRequest();
    }

    /**
     * 获取response
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        return servletRequestAttributes().getResponse();
    }

    /**
     * 获取session
     *
     * @return
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }
}
